package com.sihan.framework.etm.service.business.impl;

import com.framework.model.PageResult;
import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.sihan.framework.etm.common.CacheOperatorInfo;
import com.sihan.framework.etm.common.CommonBiz;
import com.sihan.framework.etm.common.util.EtmWebUtil;
import com.sihan.framework.etm.dto.business.*;
import com.sihan.framework.etm.entity.baseData.ToolModel;
import com.sihan.framework.etm.entity.business.ToolPosition;
import com.sihan.framework.etm.entity.business.ToolScrap;
import com.sihan.framework.etm.enums.CacheKeyName;
import com.sihan.framework.etm.mapper.baseData.ToolMapper;
import com.sihan.framework.etm.mapper.business.ScrapStandingBookMapper;
import com.sihan.framework.etm.schema.master.ScrapRecordSchema;
import com.sihan.framework.etm.service.business.ScrapStandingService;
import com.sihan.framework.etm.vo.business.*;
import lombok.RequiredArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gyz
 * @version 1.0
 * @since jdk1.8
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ScrapStandingServiceImpl extends BaseServiceImpl<ToolPosition, String> implements ScrapStandingService {

	private final ScrapStandingBookMapper scrapStandingBookMapper;
	
	private final ToolMapper toolMapper;
	
	private final CommonBiz commonBiz;
	
	public static final Object lock = new Object();

	@Override
	public PageResult<ScrapStandingBookVO> selectStandingBookPage(ScrapStandingBookDTO dto) {
		PageHelper.startPage(dto);
		List<ScrapStandingBookVO> result = scrapStandingBookMapper.selectPage(dto);
		if(null != result && !result.isEmpty()) {
			result.stream().forEach(vo->{
				vo.setDateTime(StringUtils.isBlank(vo.getDateTime())?"":vo.getDateTime().substring(0, 19));
			});
		}
		return PageUtils.toPageResult(result);
	}

	@Override
	public PageResult<ExceptionListVO> selectExceptionkListPage(ExceptionListDTO dto) {
		PageHelper.startPage(dto);
		List<ExceptionListVO> result = scrapStandingBookMapper.selectExceptionkListPage(dto);
		if(null != result && !result.isEmpty()) {
			result.stream().forEach(vo->{
				vo.setOutWarehouseTime(StringUtils.isBlank(vo.getOutWarehouseTime())?"":vo.getOutWarehouseTime().substring(0, 19));
				vo.setIntWarehouseTime(StringUtils.isBlank(vo.getIntWarehouseTime())?"":vo.getIntWarehouseTime().substring(0, 19));
			});
		}
		return PageUtils.toPageResult(result);
	}

	@Override
	public PageResult<ScrapListVO> selectScrapListPage(ExceptionListDTO dto) {
		PageHelper.startPage(dto);
		List<ScrapListVO> result = scrapStandingBookMapper.selectScrapListPage(dto);
		return PageUtils.toPageResult(result);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map getScrapDetailInfo(String scrapId) {
		BaseToolInfo baseToolMainInfo = scrapStandingBookMapper.getBaseToolMainInfo(scrapId);
		Map scrapDetailInfo = new HashMap<>();
		scrapDetailInfo.put("baseToolMainInfo", baseToolMainInfo);
		return scrapDetailInfo;
	}

	@Override
	public PageResult<ToolCheckRecordVO> getToolCheckRecode(ToolCheckRecordDTO dto) {
		if(!StringUtils.isBlank(dto.getStartDate())) {
			dto.setQueryStartTime(dto.getStartDate() + " 00:00:00:000");
		}
		if(!StringUtils.isBlank(dto.getEndDate())) {
			dto.setQueryEndTime(dto.getEndDate() + " 23:59:59:999");
		}
		PageHelper.startPage(dto);
		List<ToolCheckRecordVO> result = scrapStandingBookMapper.getToolCheckRecode(dto);
		return PageUtils.toPageResult(result);
	}
	
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	@Override
//	public PageResult<BaseToolInfo> getToolInfoList(ScrapReasonDTO dto) {
//		PageHelper.startPage(dto);
//		//synchronized (lock) {
//			String bfToolIdList = (String) CacheOperatorInfo.getMapValue(
//					CacheKeyName.BF_TOOL_ID_LIST.getValue(), CacheKeyName.BF_TOOL_ID_LIST.getValue());
//			Long scrapUserId = (long)CacheOperatorInfo.getMapValue(
//					CacheKeyName.VALIDATED_USER_ID.getValue(), 0l);
//			Map map = new HashMap();
//			map.put("userId", scrapUserId);
//			if(!bfToolIdList.equals(CacheKeyName.BF_TOOL_ID_LIST.getValue())) {
//				ToolScrap scrap = scrapStandingBookMapper.selectOne(new Condition<ToolScrap>().
//						eq("tool_id", dto.getToolId()).neq("status", -1));
//				if(null != scrap) {
//					throw new IllegalArgumentException("工器具报废重复！");
//				}
//				String[] split = bfToolIdList.split(",");
//				for (int i = 0; i < split.length; i++) {
//					if(!"0".equals(dto.getToolId()) && dto.getToolId().equals(split[i])){
//						throw new IllegalArgumentException("工器具报废重复！");
//					}
//				}
//				bfToolIdList = bfToolIdList + "," + dto.getToolId();
//				CacheOperatorInfo.setMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(), bfToolIdList);
//				if(!"0".equals(dto.getToolId())) {
//					map.put("toolId", dto.getToolId());
//					scrapStandingBookMapper.addScrapRecord(map);
//				}
////				ToolModel tool = toolMapper.selectById(Long.parseLong(dto.getToolId()));
////				if(null != tool) {
////					tool.setStatus(3);
////					toolMapper.updateById(tool);
////				}
//				List<BaseToolInfo> result = scrapStandingBookMapper.getToolInfoById();
//				return PageUtils.toPageResult(result);
//			}else {
//				CacheOperatorInfo.setMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(), dto.getToolId());
//				ToolScrap scrap = scrapStandingBookMapper.selectOne(new Condition<ToolScrap>().
//						eq("tool_id", dto.getToolId()).neq("status", -1));
//				if(null != scrap) {
//					throw new IllegalArgumentException("工器具报废重复！");
//				}
//				if(!"0".equals(dto.getToolId())) {
//					map.put("toolId", dto.getToolId());
//					scrapStandingBookMapper.addScrapRecord(map);
//				}
////				ToolModel tool = toolMapper.selectById(Long.parseLong(dto.getToolId()));
////				if(null != tool) {
////					tool.setStatus(3);
////					toolMapper.updateById(tool);
////				}
//				List<BaseToolInfo> result = scrapStandingBookMapper.getToolInfoById();
//				return PageUtils.toPageResult(result);
//			}
//		//}
//	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public PageResult<BaseToolInfo> getToolInfoList(ScrapReasonDTO dto) {
		PageHelper.startPage(dto);
		//synchronized (lock) {
			String bfToolIdList = (String) CacheOperatorInfo.getMapValue(
					CacheKeyName.BF_TOOL_ID_LIST.getValue(), CacheKeyName.BF_TOOL_ID_LIST.getValue());
			//String scrapUserId = commonBiz.checkValidatedUserId();
			//Long scrapUserId = commonBiz.checkValidatedUserId();
			String scrapUserId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.VALIDATED_USER_ID.getValue(), null);
			Map map = new HashMap();
			if(StringUtils.isBlank(scrapUserId)) {
				scrapUserId = EtmWebUtil.userId();
			}
			map.put("userId", scrapUserId);
			if(!bfToolIdList.equals(CacheKeyName.BF_TOOL_ID_LIST.getValue())) {
				ToolScrap scrap = scrapStandingBookMapper.selectOne(new Condition<ToolScrap>().
						eq("tool_id", dto.getToolId()).neq("status", -1));
				if(null != scrap) {
					throw new IllegalArgumentException("工器具报废重复！");
				}
				String[] split = bfToolIdList.split(",");
				for (int i = 0; i < split.length; i++) {
					if(!"0".equals(dto.getToolId()) && dto.getToolId().equals(split[i])){
						throw new IllegalArgumentException("工器具报废重复！");
					}
				}
				bfToolIdList = bfToolIdList + "," + dto.getToolId();
				CacheOperatorInfo.setMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(), bfToolIdList);
				if(!"0".equals(dto.getToolId())) {
					map.put("toolId", dto.getToolId());
					scrapStandingBookMapper.addScrapRecord(map);
				}
//				ToolModel tool = toolMapper.selectById(Long.parseLong(dto.getToolId()));
//				if(null != tool) {
//					tool.setStatus(3);
//					toolMapper.updateById(tool);
//				}
				List<BaseToolInfo> result = scrapStandingBookMapper.getToolInfoById();
				return PageUtils.toPageResult(result);
			}else {
				CacheOperatorInfo.setMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(), dto.getToolId());
				ToolScrap scrap = scrapStandingBookMapper.selectOne(new Condition<ToolScrap>().
						eq("tool_id", dto.getToolId()).neq("status", -1));
				if(null != scrap) {
					throw new IllegalArgumentException("工器具报废重复！");
				}
				if(!"0".equals(dto.getToolId())) {
					map.put("toolId", dto.getToolId());
					scrapStandingBookMapper.addScrapRecord(map);
				}
//				ToolModel tool = toolMapper.selectById(Long.parseLong(dto.getToolId()));
//				if(null != tool) {
//					tool.setStatus(3);
//					toolMapper.updateById(tool);
//				}
				List<BaseToolInfo> result = scrapStandingBookMapper.getToolInfoById();
				return PageUtils.toPageResult(result);
			}
		//}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addScrapTable(String toolId, String id) {
		int updateLog = scrapStandingBookMapper.updateToolException(id);
		if(updateLog == 1){
//			Map map = new HashMap();
//			map.put("userId", EtmWebUtil.userId());
//			map.put("userName", WebUtils.username());
//			map.put("toolId", toolId);
//			map.put("reason", "");
			ScrapReasonDTO dto = new ScrapReasonDTO();
			dto.setToolId(toolId);
			this.getToolInfoList(dto);
			//scrapStandingBookMapper.addScrapRecord(map);
		}else {
			throw new IllegalArgumentException("参数错误！");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteExceptionTable(String id) {
		int updateLog = scrapStandingBookMapper.updateException(id);
		if(updateLog != 1){
			throw new IllegalArgumentException("参数错误！");
		}
	}

	@Override
	public void getoutScrapList(String toolId) {
		scrapStandingBookMapper.deleleBytoolId(toolId);
		//ToolModel tool = toolMapper.selectById(Long.parseLong(toolId));
		//tool.setStatus(0);
		//toolMapper.updateById(tool);
		String bfToolIdList = (String) CacheOperatorInfo.getMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(),
				CacheKeyName.BF_TOOL_ID_LIST.getValue());
		if(!CacheKeyName.BF_TOOL_ID_LIST.getValue().equals(bfToolIdList)) {
			List<String> arrayList = new ArrayList<String>(Arrays.asList(bfToolIdList.split(",")));
			if(arrayList.contains(toolId)) {
				arrayList.remove(toolId);
				CacheOperatorInfo.setMapValue(CacheKeyName.BF_TOOL_ID_LIST.getValue(),StringUtils.join(arrayList,","));
			}
		}
	}

	@Override
	public void addScrapReason(ScrapReasonDTO dto) {
		String latestScrapId = scrapStandingBookMapper.getLatestScrapId(dto);
		dto.setScrapId(latestScrapId);
		scrapStandingBookMapper.updateScrapReason(dto);
	}

	@Override
	public void stopScanningTool() {
		//synchronized (lock) {
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_LOG.getValue(), "0");
			String readerCodeList = (String) CacheOperatorInfo.getMapValue(
					CacheKeyName.READER_CODE_LIST.getValue(), CacheKeyName.READER_CODE_LIST.getValue());
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_CODE_LIST.getValue(), 
					CacheKeyName.READER_CODE_LIST.getValue());
			if(!readerCodeList.equals(CacheKeyName.READER_CODE_LIST.getValue())) {
				String[] split = readerCodeList.split(",");
				for (int i = 1; i < split.length; i++) {
					String toolId = scrapStandingBookMapper.getToolIdBycode(split[i]);
					ScrapReasonDTO dto = new ScrapReasonDTO();
					dto.setToolId(toolId);
					getToolInfoList(dto);
				}
			}
		//}
	}

	@Override
	public void scrapSubmit() {
		commonBiz.sendIvgScanStopCommand();
		@SuppressWarnings("unchecked")
		List<ToolScrap> scaps = scrapStandingBookMapper.selectList(new Condition<ToolScrap>().
				eq("status", 0));
		List<ScrapRecordSchema> needSendScraps = new ArrayList<ScrapRecordSchema>();
		if(null != scaps && !scaps.isEmpty()) {
			scaps.stream().forEach(scrap->{
				//scrap.setStatus(3);
				scrapStandingBookMapper.updateById(scrap);
				ToolModel tool = toolMapper.selectById(scrap.getToolId());
				if(null != tool) {
//					tool.setStatus(3);
//					toolMapper.updateById(tool);
//					//借与归还
//					@SuppressWarnings("unchecked")
//					List<ToolBorrowDetail> borrowDetails = toolBorrowDetailMapper.selectList(
//							new Condition<>().eq("tool_id", scrap.getToolId()).
//							eq("has_return", 0));
//					if(null != borrowDetails && borrowDetails.size() > 0) {
//						borrowDetails.stream().forEach(borrow->{
//							borrow.setHasReturn(1);
//							borrow.setReturnTime(new Date());
//							toolBorrowDetailMapper.updateById(borrow);
//						});
//					}
//					//检验与归还
//					@SuppressWarnings("unchecked")
//					List<ToolInspectDetail> inspectDetails = inspectDetailMapper.selectList(
//							new Condition<ToolInspectDetail>().eq("tool_id", scrap.getToolId()).
//							eq("has_in_warehouse", 0));
//					if(null != inspectDetails && inspectDetails.size() > 0) {
//						inspectDetails.stream().forEach(inspect->{
//							inspect.setHasInWarehouse(1);
//							inspect.setInWarehouseTime(new Date());
//							inspectDetailMapper.updateById(inspect);
//						});
//					}
//					try {
//						ScrapRecordSchema schema = new ScrapRecordSchema();
//						schema.setEpc(tool.getCode());
//						schema.setOrgCode(masterConfig.getTerminalOrgCode());
//						schema.setScrapId(scrap.getScrapUserId());
//						schema.setScrappedMsg(scrap.getReason());
//						needSendScraps.add(schema);
//					}catch(Exception e) {
//						log.info("报废数据传输到主站异常：{}",e);
//					}
				}
			});
//			//移除检验提醒清单
//			List<Long> rfids = scaps.stream().map(ToolScrap::getToolId).collect(Collectors.toList());
//			inspectDetailMapper.updateInspectRemindIsDelete(rfids);
			//发送报废信息到主站
//			if(!needSendScraps.isEmpty()) {
//				masterConfig.sendMsgToMaster(masterConfig.getMasterApiUrl()+masterConfig.getScrapRecordApi(), 
//						needSendScraps, ApiResult.class);
//			}
			
			//发送更新的工器具状态
			//commonSendInfo.sendToolInfoByIds(rfids);
			
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_LOG.getValue(), "0");
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_CODE_LIST.getValue(), 
					CacheKeyName.READER_CODE_LIST.getValue());
		}
	}
}
